/**
 * 统一前缀
 * @type {string}
 */
var $_path=""//ajax
var $path="localhost:80";//websocket

/**
 * QQ-UI 弹框
 * dialog.show({
                title:"hello",
                content:"world",
                btn:[
                    {id:"aa",text:"aa"},
                    {id:"bb",text:"bb"},
                    {id:"cc",text:"cc"},
                ],
               aa: function (){
                    alert(1)
               },
               bb: function (){
                    alert(2)
               },
               cc: function (){
                    alert(3)
               }
            });
 *
 */
const dialog = {
    title: "",
    content: "",
    btn: [],
    templates: {
        main: `<div class="ui-dialog show">
                        <div class="ui-dialog-cnt">
                            <header class="ui-dialog-hd ui-border-b">
                            <h3></h3>
                            <i class="ui-dialog-close" data-role="button"></i>
                            </header>
                            <div class="ui-dialog-bd"></div>
                            <div class="ui-dialog-ft"></div>
                        </div>        
                    </div>`,
        btn: '<button type="button" data-role="button" > </button>'
    },
    show: function (t) {
        this.title = t["title"] ? t["title"] : "",
            this.content = t["content"] ? t["content"] : "",
            this.btn = t["btn"] ? t["btn"] : [];
        let uuid = new Date().getMilliseconds(), $this = $(this.templates["main"]).attr("dialog-id", uuid);
        $this.find("h3").html(this.title)
        $this.find(".ui-dialog-bd").html(this.content)
        $(this.btn).each((i, t) => {
            $this.find(".ui-dialog-ft").append($(this.templates.btn).html(t.text).attr("dialog-btn-id", t.id)[0]);
        })
        $("body").append($this[0]);
        $(".ui-dialog-close").click(function () {
            $this.remove();
        })
        $(this.btn).each((i, b) => {
            $("div[dialog-id='" + uuid + "'] button[dialog-btn-id='" + b.id + "']").click(t[b.id])
        })
        return $this;
    }
};

//聊天室发送消息
const send={
    templates:{
        headerUrl:"http://love.itphy.com/group1/M00/00/00/rBEPcmCo0R6ARnEgAACEhgnlCjg311.jpg",
        other:`<div class="ui-flex ui-flex-pack-start ui-flex-align-center">
            <div class="ui-avatar">
                <span style="background-image:url(http://love.itphy.com/group1/M00/00/00/rBEPcmCo0R6ARnEgAACEhgnlCjg311.jpg)"></span>
            </div>
            <div class="dialog-content-left">
                <p class="dialog-content"></p>
            </div>
        </div>`,
        me:`<div class="ui-flex ui-flex-pack-end ui-flex-align-center">
            <div class="dialog-content-right">
                <p class="dialog-content"></p>
            </div>
            <div class="ui-avatar">
                <span style="background-image:url(http://love.itphy.com/group1/M00/00/00/rBEPcmCo0R6ARnEgAACEhgnlCjg311.jpg)"></span>
            </div>
        </div>`,
        msgType:['<img >'],//0 - 图片消息模板
    },
    me: function ($this,message,type){
        let me=$(this.templates.me),content=message;
        if(type*1==0){
            content=$(this.templates.msgType[0]).attr("src","http://love.itphy.com/"+content)[0];
        }
        me.find(".dialog-content").html(content)
        $this.append(me[0])
    },
    other: function ($this,message,type){
        let other=$(this.templates.other),content=message;
        if(type*1==0){
            content=$(this.templates.msgType[0]).attr("src","http://love.itphy.com/"+content)[0];
        }
        other.find(".dialog-content").html(content)
        $this.append(other[0])
    }
}

//滚动到底部
function scrollToEnd(){
    window.scrollTo(0, document.documentElement.scrollHeight)
}

function getAsyncFunQueue() {
    return {
        funList: [],
        state: false,
        execute: null,
        add: function (fun, params) {
            this.funList.push({funName: fun, paramValue: params})
            return this;
        },
        start: function () {
            const obj = this;
            if (obj.execute != null) {
                return;
            }
            obj.execute = setInterval(function () {
                if (obj.funList.length > 0) {
                    if (!obj.state) {
                        obj.state = true;
                        let item = obj.funList.shift();
                        if (typeof (item.funName) == "function") {
                            item.funName(item.paramValue);
                        }
                    }
                } else {
                    clearInterval(obj.execute);
                    obj.execute = null;
                }
            }, 200)
        },
        close: function () {
            this.state = false;
            return this;
        }
    }
}

function commonAjax(ajaxParams, params, beforeFunction, callBackFunction, finishFunction) {
    $.ajax({
        type: ajaxParams.type,
        url: $_path+ajaxParams.url,
        dataType: ajaxParams.dataType ? ajaxParams.dataType : "json",
        contentType: ajaxParams.contentType ? "application/json;charset=utf-8" : "application/x-www-form-urlencoded",
        async: ajaxParams.async ? ajaxParams.async : true,
        headers: ajaxParams.headers,
        data: params,
        beforeSend: function (request) {
            if (typeof (beforeFunction) == 'function') {
                beforeFunction(request);
            }
        },
        success: function (data) {
            if (typeof (callBackFunction) == 'function') {
                var html = callBackFunction(data);
            }
            if (typeof (finishFunction) == 'function') {
                finishFunction();
            }
        }
    });
}

//图片压缩上传
const ImgSmall={
    reader: new FileReader(),
    img: new Image(),
    fileObj: new FormData(),
    url:"",
    finishFunction: function (){},
    save: function (){
        let $this=this;
        $.ajax({
            url: $this.url,
            type: 'POST',
            cache: false,
            data: $this.fileObj,
            processData: false,
            contentType: false,
            success: function (result) {
                typeof ($this.finishFunction)=='function'?$this.finishFunction(result.data):1==1;
            }
        });
    },
    init:function (){
        this.reader=new FileReader(),
            this.img= new Image(),
            this.fileObj= new FormData();
        return this;
    },
    toBlob: function (file){
        let $this=this.init();
        $this.img.onload=function (e){
            let canvas = document.createElement('canvas');
            let context = canvas.getContext('2d');
            // 图片原始尺寸
            var originWidth = this.width;
            var originHeight = this.height;
            // 最大尺寸限制
            var maxWidth = 200, maxHeight = 400;
            // 目标尺寸
            var targetWidth = originWidth, targetHeight = originHeight;
            // 图片尺寸超过400x400的限制
            if (originWidth > maxWidth || originHeight > maxHeight) {
                if (originWidth / originHeight > maxWidth / maxHeight) {
                    // 更宽，按照宽度限定尺寸
                    targetWidth = maxWidth;
                    targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                } else {
                    targetHeight = maxHeight;
                    targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                }
            }

            // canvas对图片进行缩放
            canvas.width = targetWidth;
            canvas.height = targetHeight;
            // 清除画布
            context.clearRect(0, 0, targetWidth, targetHeight);
            // 图片压缩
            context.drawImage($this.img, 0, 0, targetWidth, targetHeight);
            // canvas转为blob并上传
            canvas.toBlob(function (blob) {
                $this.fileObj.append("file",blob);
                $this.save()
            }, file.type || 'image/png');
        }
        $this.reader.onload = function (e) {
            $this.img.src = e.target.result;
        };
        $this.reader.readAsDataURL(file);
    },
    upload: function (e,finishFunction){
        this.url=e.url;
        this.finishFunction=finishFunction;
        this.toBlob(e.file);
    }
}
/**
 *
 ImgSmall.upload({
                file: this.files[0],
                url: "http://localhost:9999/oss"
            },(r)=>{
                console.log(r)
            });
 *
 */
